package com.hao.nettytest.controller;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import com.hao.nettytest.dto.MessageDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;


@Component
public class SocketHandler {


    //用来存已连接的客户端
    private static Map<String, SocketIOClient> clientMap = new ConcurrentHashMap<>();

    //客户端计数
    public static AtomicInteger clientCount = new AtomicInteger();


    private final SocketIOServer socketIOServer;

    @Autowired
    public SocketHandler(SocketIOServer socketIOServer) {
        this.socketIOServer = socketIOServer;
    }

    //当客户端发起连接时调用
    @OnConnect
    public void onConnect(SocketIOClient socketIOClient) {
        clientCount.incrementAndGet();
        String userID = getParamsByClient(socketIOClient);
        if (userID != null){
            clientMap.put(userID, socketIOClient);
        }

        this.sendMsg(socketIOClient, null, new MessageDto(userID,"Hello~~~NO."+clientCount));
    }

    //客户端断开连接时调用，刷新客户端信息
    @OnDisconnect
    public void onDisConnect(SocketIOClient socketIOClient) {

        if(clientCount.get() > 0) {
            clientCount.decrementAndGet();
        }

        String userID = getParamsByClient(socketIOClient);
        if (userID != null) {
            clientMap.remove(userID);
            socketIOClient.disconnect();
        }
    }

    //sendMsg发送消息事件
    @OnEvent("sendMsg")
    public void sendMsg(SocketIOClient socketIOClient, AckRequest ackRequest, MessageDto messageDto) {

        System.out.println(messageDto.getMsgContent());

        if (messageDto.getUserID() != null && clientMap.get(messageDto.getUserID()) != null) {

            SocketIOClient toClient = clientMap.get(messageDto.getUserID());
            String userID = getParamsByClient(socketIOClient);
            messageDto.setMsgContent("From "+userID+" To "+messageDto.getUserID()+" : "+messageDto.getMsgContent());
            toClient.sendEvent("receiveMsg", messageDto);
        }else{
            socketIOClient.sendEvent("receiveMsg", messageDto);
        }
    }


    //此方法为获取client连接中的参数
    private String getParamsByClient(SocketIOClient client) {
        // 从请求的连接中拿出参数（userID必须是唯一标识）
        Map<String, List<String>> params = client.getHandshakeData().getUrlParams();
        List<String> list = params.get("userID");
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    //此方法为获取client连接中的参数
    private SocketIOClient getClientByUid(String userID) {

        SocketIOClient client = clientMap.get(userID);
        return client;
    }

}

